import React, { useEffect, useState } from "react";
import { useModel } from "@umijs/max";
import { Card, Form, Input, Select, Space, Button, Cascader, Row, Col } from "antd";
import XlRadio from "@/components/Form/XlRadio";
import XlTimeRange from "@/components/Form/XlTimeRange";
import { isFba, isOverWarehouse, isPostCode, takePickUp, takeToWarese } from "@/utils/dictUtil";
import { fetchDestinationOptions } from '../../services';
import { useComponentDidMount } from "@/hooks";
import XlSelect from "@/components/Form/XlSelect";
import { useRequest } from "ahooks";
import { baseDomesticWhQueryByCode, fetchDomesticWhOptions } from "@/pages/BasicInfo/services";
import AddressManage from "../../modals/AddressManage";
import { addressTypes } from "@/constants/types";

const { Item } = Form;
const rules = [{required: true}];
const labelCol = {
  span: 3
}

const SendInfo = ({form, getDict, companyInfoForm, productInfoForm}: any) => {
  const pickupMethods = getDict('pickupMethod');
  const [addressVisible, setAddressVisible] = useState(false);
  const destTypes = getDict('destType');
  const countrys = getDict('country');
  const { areaData, fetchAreaData } = useModel('areaModel');
  const {data: warehouseList} = useRequest(fetchDomesticWhOptions);

  const [warehouseInfo, setWarehouseInfo] = useState<addressTypes | null>(null);

  const userId = Form.useWatch('userId', companyInfoForm);
  const cwhCode = Form.useWatch('cwhCode', form);


  const country = Form.useWatch('country', form);
  const destType = Form.useWatch('destType', form);

  const [codes, setCodes] = useState([]);

  const fetchFbaCodes = (params: {destType: string | undefined, country: string | undefined}) => {
    fetchDestinationOptions(params).then(
      res => {
        setCodes((res || []).map((v: any) => ({label: v?.destCode, value: v?.destCode, zip: v?.zip})));
      }
    )
  }
  // 地址簿
  const addressProps = {
    title: '地址簿',
    currentRow: {
      userId
    },
    visible: addressVisible,
    onCancel: () => {
      setAddressVisible(false);
    },
    onSubmit: (values: addressTypes) => {
      form.setFieldsValue({
        pickupContacts: values.contacts,
        pickupMobile: values.mobile,
        pickupArea: [values.province, values.city, values.area],
        pickupAddress: values.address
      });
      addressProps.onCancel();
    }
  }

  const handleCwhChange = (cwhCode: string) => {
    form.setFieldValue('cwhName', warehouseList?.find((v: any) => v.code === cwhCode)?.name);
  }
 
  useEffect(() => {
    if (cwhCode) {
      baseDomesticWhQueryByCode({code: cwhCode}).then(
        res => {
          setWarehouseInfo(res || null);
        }
      )
    } else {
      setWarehouseInfo(null);
    }
  }, [cwhCode]);

  useEffect(() => {
    if (country && destType && !isPostCode(destType)) {
      fetchFbaCodes({
        country,
        destType
      });
    } else {
      setCodes([]);
    }
  }, [country, destType]);

  useComponentDidMount(() => {
    fetchAreaData();
  })

  return (
    <>
      <Card title="收发地址信息" className="mt15">
        <Form form={form} labelCol={labelCol}>
          <Item label="收件地址" required>
            <Space>
                <Item noStyle name="destType" rules={rules}>
                  <Select style={{width: '150px'}} options={destTypes} onChange={() => {
                    form.setFieldValue('destCode', undefined);
                    productInfoForm.setFieldValue('quoteId', undefined)
                  }} />
                </Item>
                <Item noStyle name="country" rules={rules}>
                  <Select  style={{width: '150px'}} options={countrys} onChange={() => {
                    form.setFieldValue('destCode', undefined);
                    productInfoForm.setFieldValue('quoteId', undefined)
                  }} />
                </Item>
                <Item noStyle shouldUpdate={(prev, next) => (prev.destType !== next.destType || prev.country !== next.country)}>
                  {({getFieldValue}) => {
                    const destType = getFieldValue('destType');
                    // fba
                    if (isFba(destType) || isOverWarehouse(destType)) {
                      return (
                        <Item noStyle name="destCode" rules={rules}>
                          <Select 
                            onChange={() => productInfoForm.setFieldValue('quoteId', undefined)} 
                            style={{width: '150px'}}
                            showSearch 
                            allowClear 
                            options={codes}
                            filterOption={(inputValue, option) => {
                              if (!inputValue) {
                                return true;
                              }
                              return option?.label?.toLocaleUpperCase()?.indexOf(inputValue?.toLocaleUpperCase()) >= 0 || option?.zip?.indexOf(inputValue) >= 0 
                            }}
                          />
                        </Item>
                      );
                    }
                    // 邮编
                    if (isPostCode(destType)) {
                      return (
                        <Space>
                          <Item noStyle name="destCode" rules={rules}>
                            <Input onBlur={() => productInfoForm.setFieldValue('quoteId', undefined)} placeholder="请输入邮编" />
                          </Item>
                          <Item noStyle name="destState" rules={[{required: true, message: '请输入目的州'}]}>
                            <Input placeholder="目的州"  />
                          </Item>
                          <Item noStyle name="destCity" rules={[{required: true, message: '请输入目的城市'}]}>
                            <Input placeholder="目的城市" />
                          </Item>
                          <Item noStyle name="destAddress" rules={[{required: true, message: '请输入详情地址'}]}>
                            <Input placeholder="详情地址" />
                          </Item>
                        </Space>
                      );
                    }
                  }}
                </Item>
            </Space>
          </Item>
          <Item label="交货方式" name="pickupWay" rules={rules}>
            <XlRadio.ButtonRadioGutterGroup onChange={() => {
              form.setFieldsValue({
                cwhCode: null,
                pickupContacts: null,
                pickupMobile: null,
                pickupArea: null,
                pickupAddress: null
              });
            }} options={pickupMethods} />
          </Item>
          <Item noStyle shouldUpdate={(prev,next) => prev.pickupWay !== next.pickupWay}>
            {({getFieldValue}) => {
              const pickupWay = getFieldValue('pickupWay');
              if (takeToWarese(pickupWay)) {
                return (
                  <Item label="收货仓库" required>
                    <Space>
                      <Item name="cwhCode" rules={rules} noStyle>
                        <XlSelect
                          allowClear
                          showSearch
                          optionFilterProp="label"
                          style={{width: 300}}
                          options={warehouseList}
                          onChange={handleCwhChange}
                          dataLabel="name"
                          dataValue="code"
                        />
                      </Item>
                      <Item name="cwhName" hidden noStyle>
                        <Input />
                      </Item>
                      {
                        warehouseInfo && (
                          <Space style={{flexWrap: 'wrap', backgroundColor: '#f5f5f5', borderRadius: '10px', padding: '10px'}}>
                            <span>地址：{[warehouseInfo?.province, warehouseInfo?.city, warehouseInfo?.area, warehouseInfo?.address].join('')}</span>
                            <span>仓库营业时间 {warehouseInfo?.openingTime}——{warehouseInfo?.closingTime}</span> 
                            <span>联系电话：{warehouseInfo?.tel}</span>
                            <span>备注：{warehouseInfo?.remark}</span>
                          </Space>
                        )
                      }
                    </Space>
                  </Item>
                );
              }
              if (takePickUp(pickupWay)) {
                return (
                  <>
                    <Item label="取货联系人" required style={{marginBottom: 0}}>
                      <Space>
                        <Item name="pickupContacts" rules={rules}>
                          <Input style={{width: 250}} />
                        </Item>
                        <Item label="联系电话" name="pickupMobile" rules={rules}>
                          <Input style={{width: 250}} maxLength={11} />
                        </Item>
                        {userId && <Button style={{marginBottom: 20}} onClick={() => setAddressVisible(true)} type="link">地址簿</Button>}
                      </Space>
                    </Item>
                    <Item label="取货地址" required>
                      <Space>
                        <Item name="pickupArea" noStyle>
                          <Cascader showSearch style={{width: 250}} fieldNames={{label: 'name', value: 'name', children: 'children'}} options={areaData} />
                        </Item>
                        <Item name="pickupAddress" noStyle rules={rules}>
                          <Input style={{width: '300px'}} />
                        </Item>
                      </Space>
                    </Item>
                  </>
                );
              }
            }}
          </Item>
          <Item noStyle shouldUpdate={(prev, next) => prev.pickupWay !== next.pickupWay}>
            {({getFieldValue}) => {
              const pickupWay = getFieldValue('pickupWay');
              if (takePickUp(pickupWay)) {
                return (
                  <Item label="预约提货时间" name="pickUpDateTime" rules={rules}>
                    <XlTimeRange />
                  </Item>
                );
              }
              if (takeToWarese(pickupWay)) {
                return (
                  <Item label="预约送仓时间" name="pickUpDateTime" rules={rules}>
                    <XlTimeRange />
                  </Item>
                );
              }
            }}
          </Item>
        </Form>
      </Card>
      {addressVisible && <AddressManage {...addressProps} />}
    </>
  );
}
export default SendInfo;